import React, { FC, Suspense, useState, useEffect } from 'react';
import { Layout, Menu, theme, Avatar, Popover, Button } from 'antd';
import { Outlet, useNavigate, useLocation } from 'react-router-dom';
import { MenuItemType } from 'antd/es/menu/hooks/useItems';
import './app.less';
import { menuConfig } from './config/menuConfig';
import CommonDescription from '@/common/CommonDescription';

const { Header, Content, Footer, Sider } = Layout;

const _App: FC = () => {
  const navigate = useNavigate();
  const { pathname } = useLocation();
  const [selectedKeys, setSelectedKeys] = useState<string[]>([]);

  const {
    token: { colorBgContainer },
  } = theme.useToken();

  useEffect(() => {
    setSelectedKeys([pathname.split('/app').join('').substring(1)]);
  }, [pathname]);

  const menuClick = (e: MenuItemType) => {
    const url: any = e.key;
    navigate(url);
  };
  const menuItem = menuConfig.find((o) => o.path === selectedKeys?.[0]);
  return (
    <Layout className="layout-layout">
      <Sider breakpoint="lg" collapsedWidth="0">
        <div className="logo" />
        <Menu
          theme="dark"
          mode="inline"
          items={menuConfig.map((item) => ({
            key: item.path,
            label: item.title,
            icon: <item.icon />,
          }))}
          onClick={menuClick}
          selectedKeys={selectedKeys}
        />
      </Sider>
      <Layout>
        <Header className="header" style={{ background: colorBgContainer }}>
          <div className="left"></div>
          <div className="right">
            <Popover
              content={
                <div>
                  <Button
                    type="primary"
                    onClick={() => {
                      document.cookie = 'userKey=; path=/;';
                      window.location.reload();
                    }}
                  >
                    登出
                  </Button>
                </div>
              }
            >
              <Avatar src={require('@/assets/img/avatar1.jpg')} className="avatar" />
            </Popover>
          </div>
        </Header>
        <Content style={{ margin: '24px 16px 0' }}>
          <div
            style={{
              padding: 24,
              background: colorBgContainer,
              height: '100%',
              overflow: 'auto',
            }}
          >
            <Suspense fallback={<h1>loading....</h1>}>
              {menuItem && <CommonDescription navProps={menuItem.navProps} navName={menuItem.title} />}
              <Outlet />
            </Suspense>
          </div>
        </Content>
        <Footer style={{ textAlign: 'center' }}>Copyright © 保定商科工贸技工学校</Footer>
      </Layout>
    </Layout>
  );
};

export default _App;
